package com.qingkai.onlineshop.presentation.product

import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import com.qingkai.onlineshop.app.Route
import com.qingkai.onlineshop.data.AppDatabase
import kotlinx.coroutines.flow.MutableStateFlow
import kotlinx.coroutines.flow.SharingStarted
import kotlinx.coroutines.flow.onStart
import kotlinx.coroutines.flow.stateIn
import kotlinx.coroutines.flow.update
import kotlinx.coroutines.launch

/**
 *作者：created by 89270 on 2025/6/13 15:50
 *描述：
 */
class ProductViewModel(private val appDatabase: AppDatabase, private val param: Route.Product) :
    ViewModel() {
    private val _mState = MutableStateFlow(ProductState())
    val state = _mState.onStart { initItems() }
        .stateIn(viewModelScope, SharingStarted.WhileSubscribed(5000), _mState.value)

    private fun initItems() {
        viewModelScope.launch {
            val itemsByCategory = appDatabase.itemDao().getItemsByCategory(param.categoryId)
            _mState.update { it.copy(items = itemsByCategory) }
        }
    }
}